package com.zhixi100.orderservice.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zhixi100.framework.common.ObjectRestResponse;
import com.zhixi100.framework.utils.RestResponseUtils;
import com.zhixi100.orderservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * author:tommy
 * date:2018/12/13
 */
@RestController
@RequestMapping("/v1")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/find/{orderId}")
    public ObjectRestResponse findById(@PathVariable("orderId") int orderId) {
        ObjectRestResponse result = RestResponseUtils.success();
        result.setData(orderService.findById(orderId));
        return result;
    }

    @PostMapping("/save")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object saveOrder(@RequestParam("productId") int productId,
                            HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("user");

        ObjectRestResponse result = RestResponseUtils.success();

        result.setData(orderService.saveOrder(obj, productId));
        return result;
    }

    public Object saveOrderFail(int productId, HttpServletRequest request) {

//        String saveOrder = "save-order";
//        String ip = request.getRemoteAddr();

//        Object sendSms = redisTemplate.opsForValue().get(saveOrder);
//
//        new Thread(() -> {
//            if (sendSms == null) {
//                System.out.println("下单失败，执行发送短信，IP=" + ip);
//                //发送短信
//                //保存到redis中
//                redisTemplate.opsForValue().set(saveOrder, "save-order-fail", 20, TimeUnit.SECONDS);
//            } else {
//                System.out.println("已发送短信，不用重复发送");
//            }
//        }).start();

        Map res = new HashMap();
        res.put("code", -1);
        res.put("msg", "抢购的人太多，您被挤出来了，请稍后重试！");
        return res;
    }
}
